--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:47:35
--
-- IMSimpleView

local TabsBtn = require("app.widget.TabsBtn")
local IMVoiceRender = import(".renders.IMVoiceRender")
local IMSimpleRankRender = import(".renders.IMSimpleRankRender")

local IMTeamPanel = import(".IMTeamPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.IMSimpleScene

local MAX_ITEM_CNT = 4
local UNABLE_OPACITY = 128

function ClassRef:init()
	self._battlePanelIdx = nil -- 战斗中聊天切页索引缓存

	------ Panel ------
	local panel = self._ui.Panel
	self._panelInitPosY = panel:getPositionY()

	-- msg list
	display.uiAddClick(self._ui.Panel_minichat, function()
			executeFunc(self._onOperate, "showRoom")
		end)
	self._msgList = self._ui.Panel_minichat:getChildByName("message")
	self._msgList:setTouchEnabled(false)
	self._msgList:setClippingEnabled(true)
	self._listSize = self._msgList:getContentSize()

	-- msg/battle
	local btns = {
		self._ui.Panel_battle:getChildByName("Button_chat"),
		self._ui.Panel_battle:getChildByName("Button_rank"),
	}
	local binds = {
		self._ui.Panel_minichat,
		self._ui.Panel_count
	}
	local function onTabsBtn(index, btn)
		if self._panelIdx then
			self._panelIdx = index
			if self._isBattle then
				self._battlePanelIdx = index
			end
			self:switchPanel()
		else
			self._panelIdx = index
			if self._isBattle then
				self._battlePanelIdx = index
			end
		end
	end
	self._tabsBtn = TabsBtn.new(btns, onTabsBtn, nil, binds)

	self._rankRenders = {0, 0, 0, 0}
	for i,v in ipairs(self._rankRenders) do
		local node = self._ui.Panel_count:getChildByName("Panel_" .. i)
		local render = IMSimpleRankRender.create(node)
		self._rankRenders[i] = render
	end

	------ Panel_btn ------
	local btnPanel = self._ui.Panel_btn
	-- VoiceRender
	self._renders = {
		IMVoiceRender.create(btnPanel:getChildByName("Button_world"), "world"),
		IMVoiceRender.create(btnPanel:getChildByName("Button_team"), "team"),
		IMVoiceRender.create(btnPanel:getChildByName("Button_guild"), "guild"),
	}
	for _,render in ipairs(self._renders) do
		render:setExtendRect(true)
	end

	-- morePanel set
	local morePanel = btnPanel:getChildByName("Panel_more")
	self._morePanel = morePanel
	morePanel:setVisible(false)
	display.nodeRemoveForNotHit(morePanel, function()
		if morePanel:isVisible() then
			self:performWithDelay(function() self:_hideMorePanel() end, 0)
		end
	end)
	btnPanel:getChildByName("Button_more"):addClickEventListener(function(sender)
		if not morePanel:isVisible() then
			self:_showMorePanel()
		end
	end)

	self._moreBtns = {
		morePanel:findChild("Panel_world"),
		morePanel:findChild("Panel_team"),
		morePanel:findChild("Panel_guild"),
	}

	for _,btn in ipairs(self._moreBtns) do
		display.setCascadeOpacityEnabled(btn, true)
	end

	self._moreBtns[2]:setOpacity(UNABLE_OPACITY)
	self._moreBtns[2]:setTouchEnabled(false)
	self._moreBtns[3]:setOpacity(UNABLE_OPACITY)
	self._moreBtns[3]:setTouchEnabled(false)

	for i,btn in ipairs(self._moreBtns) do
		display.uiAddClick(btn, function()
			if self._curChannel ~= i then
				self._renders[self._curChannel]:setVisible(false)
				self._renders[i]:setVisible(true)

				self._moreBtns[self._curChannel]:getChildByName("selected_btn"):setBright(true)
				btn:getChildByName("selected_btn"):setBright(false)
				self._curChannel = i
			end
		end)
	end

	-- 组队语言panel
	self._teamPanel = IMTeamPanel.create(btnPanel:getChildByName("node_set"))
	self._teamPanel:refresh(false)
	self._teamPosX = self._teamPanel:getPositionX()

	-- tipPanel tip
	local tipPanel = self._ui["batt_chat_tips"]
	self._tipPanel = tipPanel
	tipPanel:setVisible(false)
	display.nodeRemoveForNotHit(tipPanel, function()
		if tipPanel:isVisible() then
			self:performWithDelay(function() self:_hideTipPanel() end, 0)
		end
	end)
	self._tipBtn = self._ui["btn_tips"]
	if app:isInnerEma() or app:isInnerPwrd() then
		tipPanel:setPositionX(11)
		self._tipBtn:setPositionX(11)
	end
	self._tipBtnPosX = self._tipBtn:getPositionX()
	self._tipBtn:addClickEventListener(function(sender)
		if not tipPanel:isVisible() then
			self:_showTipPanel()
		end
	end)

	self._imBtn = self._ui["btn_im"]
	self._imBtnPosX = self._tipBtn:getPositionX()
	self._imBtn:addClickEventListener(function(sender)
		executeFunc(self._onOperate, "showRoom")
	end)

	local con = tipPanel:getChildByName("Panel")
	local texts = {0,0,0,0}
	for i=1,4 do
		local btn = con:getChildByName("Button_" .. i)
		btn:addClickEventListener(function()
			local content = UD.setting:getBattleTalkContent(i)
			executeFunc(self._onOperate, "quickMsg", content)
			self:_hideTipPanel()
		end)

		local text = con:getChildByName("Text_" .. i)
		texts[i] = text
	end
	self._tipTexts = texts
end

function ClassRef:show(showType, posY, isBattle, battleType)
	-- print("IMSimpleView.show")
	self:setVisible(true)

	self:refresh(showType, posY, isBattle, battleType)
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
	self._teamPanel:onOperate(cb)
end

function ClassRef:_showMorePanel()
	self._morePanel:setVisible(true)
end

function ClassRef:_hideMorePanel()
	self._morePanel:setVisible(false)
end

function ClassRef:_showTipPanel()
	self._tipPanel:setVisible(true)

	for i,text in ipairs(self._tipTexts) do
		local content = UD.setting:getBattleTalkContent(i)
		if content then
			text:setString(string.uomitstr(content,Constant.BattleTalkShowEditNum))
		end
	end
end

function ClassRef:_hideTipPanel()
	self._tipPanel:setVisible(false)
end

function ClassRef:_refreshChannel()
	for i,render in ipairs(self._renders) do
		render:setVisible(i==self._curChannel)
	end
end

function ClassRef:updateWorld(open)
	local opacity = open and 255 or UNABLE_OPACITY
	display.setBtnTouchEnable(self._renders[1], open)
	self._renders[1]:setOpacity(opacity)

	display.setBtnTouchEnable(self._ui.Button_more, open)
	self._ui.Button_more:setOpacity(opacity)

	self._moreBtns[1]:setOpacity(opacity)
	self._moreBtns[1]:setTouchEnabled(open)
end

function ClassRef:updateTeam(hasTeam, hasMic, hasSpeaker)
	-- print("IMSimpleView.updateTeam", hasTeam, hasMic, hasSpeaker, self._isBattle)
	self._hasTeam = hasTeam
	self._tipBtn:setVisible(self._isBattle and hasTeam)

	local opacity = hasTeam and 255 or UNABLE_OPACITY
	self._moreBtns[2]:setOpacity(opacity)
	self._moreBtns[2]:setTouchEnabled(hasTeam)

	self._teamPanel:refresh(hasTeam, hasMic, hasSpeaker)
	if hasTeam then
		self._teamPanel:setPositionX(self._isBattle and self._teamPosX or self._tipBtnPosX)
	end

	if not hasTeam and self._curChannel == 2 then
		self._moreBtns[2]:getChildByName("selected_btn"):setBright(true)
		self._moreBtns[1]:getChildByName("selected_btn"):setBright(false)
		self._curChannel = 1
		self:_refreshChannel()
	end
end

function ClassRef:updateMicAndSpeakBtnState(type, open)
	print("IMSimpleView.updateMicAndSpeakBtnState", type, open)
	self._teamPanel:updateMicAndSpeakBtnState(type, open)
end

function ClassRef:updateGuild(hasGuild)
	self._moreBtns[3]:setTouchEnabled(hasGuild)
	self._moreBtns[3]:setOpacity(hasGuild and 255 or UNABLE_OPACITY)
	if not hasGuild and self._curChannel == 3 then
		self._moreBtns[3]:getChildByName("selected_btn"):setBright(true)
		self._moreBtns[1]:getChildByName("selected_btn"):setBright(false)
		self._curChannel = 1
		self:_refreshChannel()
	end
end

function ClassRef:isMsgListVisible()
	return self._ui.Panel:isVisible()
end

-- 获取最新item的data，用来剔除相同的数据渲染
function ClassRef:getNewItemData()
	local items = self._msgList:getItems()
	if #items > 0 then
		return items[1]:getData()
	end
	return
end

function ClassRef:refresh(showType, posY, isBattle, battleType)
	if showType == Enums.IMSimpleShowType.all then
		self._ui.Panel_btn:setVisible(true)
		self._ui.Panel:setVisible(true)
	elseif showType == Enums.IMSimpleShowType.btn then
		self._ui.Panel_btn:setVisible(true)
		self._ui.Panel:setVisible(false)
	elseif showType == Enums.IMSimpleShowType.msgs then
		self._ui.Panel_btn:setVisible(false)
		self._ui.Panel:setVisible(true)
	end
	if self._ui.Panel:isVisible() then
		self._ui.Panel:setPositionY(self._panelInitPosY + posY)
	end

	if app:isInnerEma() or app:isInnerPwrd() then
		self._ui.Panel_btn:setVisible(false) -- 海外版没有语音功能
	end

	self._curChannel = self._curChannel or 1
	self:_refreshChannel()

	for i,btn in ipairs(self._moreBtns) do
		btn:getChildByName("selected_btn"):setBright(i ~= self._curChannel)
	end

	local idx = 1
	self._isBattle = isBattle
	self._battleType = battleType
	self._tabsBtn:getBtn(2):setVisible(isBattle)
	local visibleTipBtn = isBattle and self._hasTeam and (battleType ~= Enums.EBattleType.BtType_Melee)
	self._tipBtn:setVisible(visibleTipBtn)
	local visibleIMBtn = isBattle and battleType == Enums.EBattleType.BtType_Melee
	self._imBtn:setVisible(visibleIMBtn)

	if self._hasTeam then
		self._teamPanel:setPositionX(self._isBattle and self._teamPosX or self._tipBtnPosX)
	end

	if isBattle then
		idx = self._battlePanelIdx or ( self._panelIdx or 1 )
	end
	self:switchPanel(idx)
end

function ClassRef:refreshMsgs(msgs, channelIdx)
	self._msgList:removeAllItems()
	local len = #msgs
	if len > 0 then
		local start = math.max(len-MAX_ITEM_CNT+1, 1)
		for i=start,len do
			self:addNewMsgItem(msgs[i])
		end
	end
	if channelIdx then
		self:refreshChatBtn(channelIdx)
	end
end

function ClassRef:clearMsgs()
	self._msgList:removeAllItems()
end

function ClassRef:refreshRanks(ranks)
	ranks = ranks or {}
	for i,render in ipairs(self._rankRenders) do
		render:setData(ranks[i])
	end
end

function ClassRef:switchPanel(idx)
	if idx then
		self._panelIdx = idx
		if self._isBattle then
			self._battlePanelIdx = idx
		end
		self._tabsBtn:setSelected(idx)
	end

	executeFunc(self._onOperate, "switchPanel", self._panelIdx)
end

-- 限制一条信息只能一行
-- function ClassRef:createItem(msg)
-- 	local itemHei = self._listSize.height / MAX_ITEM_CNT
-- 	local item = ccui.Layout:create()
-- 	item.data = msg
-- 	item.getData = function(item)
-- 		return item.data
-- 	end
-- 	-- item:setClippingEnabled(true)
-- 	item:setContentSize(cc.size(self._listSize.width, itemHei))

-- 	local params = {KEY_FONT_SIZE=18, KEY_FONT_FACE=Res.font, KEY_VERTICAL_SPACE=1}
-- 	local text = ccui.RichText:createWithXML(msg:getSimpleTextXml(), params)
-- 	text:setEnabled(false)
-- 	text:setTouchEnabled(false)
-- 	text:ignoreContentAdaptWithSize(false)
-- 	text:setWrapMode(1)
-- 	text:setAnchorPoint(cc.p(0,1))
-- 	text:setContentSize(cc.size(self._listSize.width, 0))

-- 	text:setOpenUrlHandler(function() end)
-- 	text:formatText()

-- 	local textSize = text:getFormatSize()
-- 	text:setContentSize(textSize)
-- 	text:setPosition(0, itemHei)

-- 	-- 超出范围的child，remove掉，避免使用clipping
-- 	if textSize.height > (itemHei+1) then
-- 		local children = text:getChildren()
-- 		local len = #children
-- 		for i=len,1,-1 do
-- 			local child = children[i]
-- 			local pos = cc.p(child:getPosition())
-- 			if pos.y < (textSize.height - itemHei - 1) then
-- 				child:removeFromParent()
-- 			else
-- 				break
-- 			end
-- 		end
-- 	end

-- 	item:addChild(text)
-- 	return item
-- end

-- 每条信息按实际宽高
function ClassRef:createItem(msg)
	local item = ccui.Layout:create()
	item.data = msg
	item.getData = function(item)
		return item.data
	end

	local params = {KEY_FONT_SIZE=19, KEY_VERTICAL_SPACE=2}
	if app:isInnerTencent() then
		params.KEY_FONT_FACE = Res.font
	end
	local text = ccui.RichText:createWithXML(msg:getSimpleTextXml(), params)
	text:setEnabled(false)
	text:setTouchEnabled(false)
	text:ignoreContentAdaptWithSize(false)
	-- text:setWrapMode(1)
	text:setAnchorPoint(cc.p(0,1))
	text:setContentSize(cc.size(self._listSize.width, 0))

	text:setOpenUrlHandler(function() end)
	text:formatText()

	local textSize = text:getFormatSize()
	textSize.width = self._listSize.width
	text:setContentSize(textSize)
	text:setPosition(0, textSize.height)

	item:setContentSize(textSize)
	item:addChild(text)
	return item
end

function ClassRef:addNewMsgItem(msg)
	local items = self._msgList:getItems()
	local count = #items
	if count >= MAX_ITEM_CNT then
		self._msgList:removeItem(0)
	end

	local item = self:createItem(msg)
	self._msgList:pushBackCustomItem(item)

	self._msgList:refreshView()
	self._msgList:jumpToBottom()

	-- self._msgList:scrollToBottom(0.1, true)
end

function ClassRef:updateMsg(msg)
	local items = self._msgList:getItems()
	local index
	for i,v in ipairs(items) do
		if v:getData() == msg then
			index = i
			break
		end
	end
	if index then
		local item = self:createItem(msg)
		self._msgList:removeItem(index - 1)
		self._msgList:insertCustomItem(item, index - 1)
		self._msgList:refreshView()
	end
end

function ClassRef:refreshChatBtn(channelIdx)
	local selectedBtnNormalPath = "art/im_icon/chatbtn_p_"..channelIdx..".png"
	local selectedBtnBrightPath = "art/im_icon/chatbtn_n_"..channelIdx..".png"
	self._tabsBtn:getBtn(1):loadTextures(selectedBtnNormalPath, selectedBtnBrightPath, selectedBtnBrightPath)
end

return ClassRef
